<template>
  <div>
      <n-card title="大模型 CHECKPOINT">
          <template #header-extra>

            <n-select size="small" v-model:value="pullStation" :options="pullStations" style="width: 200px;margin-right: 5px;margin-left: 5px;"></n-select>
            <n-button type="primary" size="small" @click="scannerModelInfo" :loading="scannerLoading">一键拉取</n-button>
          </template>
          <n-grid  :cols="4" :x-gap="5" :y-gap="5">
            <n-gi v-if="modelOption.length >0" v-for="model in modelOption">
              <n-card>
                <template #cover>
                  <div class="image-container-lora">
                    <n-image preview-disabled
                             :src="fileFunction.getSDModelImage(model.modelName,'checkpoint')" class="centered-image-lora"/>
                  </div>
                </template>
                <n-ellipsis style="width: 100%">
                  {{ model.modelName }}
                </n-ellipsis>
                <template #footer>
                  <n-space justify="space-between">
                      <n-upload
                          :custom-request="(uploadOption) => customRequest(uploadOption,model,'checkpoint')"
                      >
                          <n-button size="small" type="primary">上传图片</n-button>
                      </n-upload>
                  </n-space>
                </template>
              </n-card>
            </n-gi>
          </n-grid>
      </n-card>

      <n-card title="Lora">
        <n-grid  :cols="4" :x-gap="5" :y-gap="5">
          <n-gi v-if="loraList.length >0" v-for="lora in loraList">
            <n-card>
              <template #cover>
                <div class="image-container-lora">
                  <n-image preview-disabled :src="fileFunction.getSDModelImage(lora.modelName,'Lora')" class="centered-image-lora"/>
                </div>
              </template>
              <n-ellipsis style="width: 100%">
                {{ lora.modelName }}
              </n-ellipsis>
              <template #footer>
                <n-space justify="space-between">
                    <n-upload
                        :custom-request="(uploadOption) => customRequest(uploadOption,lora,'lora')"
                    >
                        <n-button size="small" type="primary">上传图片</n-button>
                    </n-upload>
                </n-space>
              </template>
            </n-card>
          </n-gi>
        </n-grid>
      </n-card>



    <n-modal
        v-model:show="showProgressModal"
        :mask-closable="false"
        preset="dialog"
        title="拉取图片进度"
        negative-text="关闭"
        @after-leave="taskStatus = false"
        @negative-click="taskStatus = false;showProgressModal=false;"
    >
      <n-grid>
        <n-grid-item :span="24">
          总数: {{taskInfo.totalNum}}  成功:{{taskInfo.successNum}}  失败:{{taskInfo.failNum}}
        </n-grid-item>
        <n-grid-item :span="24">
          <n-space vertical>
            <n-progress
                type="line"
                :percentage="Math.round(( ( taskInfo.successNum + taskInfo.failNum) / taskInfo.totalNum) * 100)"
                :height="24"
                :border-radius="4"
                :fill-border-radius="0"
            />
          </n-space>
        </n-grid-item>
      </n-grid>
    </n-modal>

  </div>
</template>
<script lang="ts" setup>
import {onMounted, ref} from "vue";
import {resourceController} from "@/api/resource/resourceController.api";
import fileFunction from "@/libs/globalFunction/file";
import {sdControllerApi} from "@/api/sd/sdController.api";
import {NButton, UploadCustomRequestOptions} from "naive-ui";


const modelOption = ref([])
const loraList = ref([])
const resourceOption = ref([])
const scannerLoading = ref(false)
const showProgressModal =  ref(false)
const taskStatus =  ref(false)
const pullStations = ref([
  {label: 'C站 - 注: 需要配置代理 ', value: 'civitai'}
  // ,
  // {label: 'liblib', value: 'liblib'}
])
const pullStation = ref('civitai')

const taskInfo = ref({
  totalNum: 0,
  successNum: 0,
  failNum: 0
})


const props = defineProps({
  resourceId: {
    type: String,
    required: true
  }
})


onMounted(() => {
  getResourceConfig()
})



// 获取SD资源详情
const getResourceConfig = () => {
  resourceController.getReousceConfig(props.resourceId).then(res => {
    if (res.code === 200) {
      modelOption.value = res.data.modelList
      loraList.value = res.data.loraList
    } else {
      window.$message.error(res.msg)
    }
  })
}

const scannerModelInfo = () =>{
  showProgressModal.value = true
  taskStatus.value = true
  startScannerTask()
}


const startScannerTask = async () =>{

  taskInfo.value.totalNum = 0
  taskInfo.value.failNum = 0
  taskInfo.value.successNum = 0
  if (modelOption.value){
    taskInfo.value.totalNum = modelOption.value.length
  }
  if (loraList.value){
    taskInfo.value.totalNum = taskInfo.value.totalNum + loraList.value.length
  }

  for (const model of modelOption.value) {
    if (taskStatus.value == false){
      break
    }
    const param = {
      modelName: model.modelName,
      station: pullStation.value,
      type: 'Checkpoint'
    }
     await sdControllerApi.scannerModel(param).then(res => {
      if (res.code === 200) {
        if (res.data == true){
          taskInfo.value.successNum ++
        }else {
          taskInfo.value.failNum ++
        }
      } else {
        taskInfo.value.failNum ++
      }
    }).catch(err => {
       taskInfo.value.failNum ++
    })
  }



  for (const loraModel of loraList.value){
    if (taskStatus.value == false){
      break
    }
    const param = {
      modelName: loraModel.modelName,
      station: pullStation.value,
      type: 'LORA'
    }
    await sdControllerApi.scannerModel(param).then(res => {
      if (res.code === 200) {
        if (res.data == true){
          taskInfo.value.successNum ++
        }else {
          taskInfo.value.failNum ++
        }
      } else {
        taskInfo.value.failNum ++
      }
    }).catch(err => {
      taskInfo.value.failNum ++
    })
  }
}

const customRequest = (uploadOption: UploadCustomRequestOptions, model:any,type:string) => {
    const reader = new FileReader();
    //@ts-ignore
    reader.readAsDataURL(uploadOption.file.file);
    reader.onloadend = () => {
        let image = new Image()
        image.src = reader.result
        //@ts-ignore
        model.src = reader.result
        uploadModelImage(reader.result, model.modelName, type,'SD')
    };
}

const uploadModelImage = (base64:string, modelName:string, type:string, engine:string) =>{
    if(base64 && base64.startsWith('data:image')){
        base64  = base64.split(';base64,')[1]
    }
    sdControllerApi.uploadModelImage({
        base64: base64,
        modelName: modelName,
        modelType: type,
        engine: engine
    }).then(res => {
        modelOption.value =  []
        loraList.value = []
        getResourceConfig()
        if(res.code == 200){
            window.$message.success('上传成功')
        }
    })
}

</script>



<style scoped>

.image-container-lora {
  height: 250px; /* 设置容器的固定高度 */
  display: flex; /* 使用Flex布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}

.centered-image-lora {
  max-height: 100%; /* 图片的最大高度为容器高度，宽度会自动适应宽高比例 */
  max-width: 100%; /* 图片的最大宽度为容器宽度，高度会自动适应宽高比例 */
}

.selected {
  border: 3px solid #8250df;
}


</style>
